package org.kl.bf.web.basic;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.CodeValues;
import org.kl.bf.entity.basic.Function;
import org.kl.bf.entity.basic.Menu;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.service.basic.CodeValuesService;
import org.kl.bf.service.basic.FunctionService;
import org.kl.bf.service.basic.MenuService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.utils.Collections3;
import org.springside.modules.web.MediaTypes;

/**
 * 角色管理
 * 
 * @author Qken
 * @date 2014-3-24
 */
@Controller
@RequestMapping(value = "/basic/function")
public class FunctionController extends BasicController {

	@Autowired
	private FunctionService functionService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private CodeValuesService codeValuesService;

	@RequiresPermissions("menu:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/functionList";
	}

	@RequiresPermissions("menu:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<Function> functions = functionService.getFunction(searchParams, pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(functions.getContent());
		grid.setTotal((int) functions.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequiresPermissions("menu:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("function") Function function, RedirectAttributes redirectAttributes) {
		try {
			functionService.saveFunction(function);
			return ajaxMsg("更新成功", true, null);
		} catch (Exception e) {
			return ajaxMsg("更新失败:" + e.getMessage(), false, null);
		}
	}

	@RequiresPermissions("menu:update")
	@RequestMapping(value = "batchAdd/{menuId}", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String batchAdd(@PathVariable("menuId") String menuId) {
		try {
			Menu menu = menuService.getMenu(menuId);
			if (menu != null) {
				List<CodeValues> cvList = codeValuesService.findByTableCode(BasicConstants.TABLECODE_MENUNORMALBUTTON);
				for (CodeValues cv : cvList) {
					List<Function> fList = functionService.getFunctionByNoAndMenuId(cv.getCodeName(), menu.getId());
					if (Collections3.isEmpty(fList)) {
						Function function = new Function();
						function.setMenu(menu);
						// function.setMenuId(menu.getId());
						function.setFunctionName(cv.getCodeValue());
						function.setFunctionNo(cv.getCodeName());
						functionService.saveFunction(function);
					}
				}
			}
			return ajaxMsg("批量生成成功", true, null);
		} catch (Exception e) {
			return ajaxMsg("批量生成失败:" + e.getMessage(), false, null);
		}
	}

	@RequiresPermissions("menu:delete")
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			functionService.deleteFunction(id);
			return ajaxMsg("删除成功", true, null);
		} catch (Exception e) {
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
	}

	@RequiresPermissions("menu:delete")
	// @RequiresPermissions({ "config:delete" })
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = functionService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	@RequiresPermissions("menu:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		List<Function> functions = functionService.getAllFunction(searchParams,sortType, orderType);
		super.export(Function.class, response, functions, "功能管理");
		return null; 
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getMenu(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("function", functionService.getFunction(id));
		}
	}
}
